/*
 * Copyright (c) 2023-7-17
 * 说明: 系统的用户模型更新
 */

package user

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"mongoDB"
)

func (u *User) Save(ctx context.Context, updateOptions ...*options.UpdateOptions) (*mongo.UpdateResult, error) {
	updateOptions = append(updateOptions, options.Update().SetUpsert(true))
	if u.ID.IsZero() {
		u.ID = primitive.NewObjectID()
	}
	return u.GetCollection().UpdateByID(ctx, u.ID, bson.D{
		{"$set", u},
	}, updateOptions...)
}

func (u *User) Update(ctx context.Context, dataFields *bson.D, options ...*options.UpdateOptions) (*mongo.UpdateResult, error) {
	var updateErr error
	defer func() {
		go func() { // 异步修改更改时间保存
			if updateErr != nil {
				return
			}
			_, err := u.GetCollection().UpdateByID(ctx, u.ID, bson.D{
				{"$set", bson.D{
					*mongoDB.CommonUpdateTimeFieldWithCurrentTime(),
				}},
			})
			if err != nil {
				fmt.Println("user 方法修改更改时间错误," + err.Error())
			}
		}()
	}()
	updateResult, updateErr := u.GetCollection().UpdateByID(ctx, u.ID, dataFields, options...)
	return updateResult, updateErr
}

func (u *User) Delete(ctx context.Context) error {
	delFields := bson.D{}
	delFields = append(delFields, *mongoDB.CommonDeleteWriteFields()...)
	_, err := u.Update(ctx, &bson.D{
		{"$set", delFields},
	})
	return err
}
